<template>
    <Layout>
        <Form ref="queryForm" :model="dataToQuery" :label-width="120">
            <Row class="query-form">
                <Col span="8">
                    <FormItem label="二级集团：">
                        <two-level-org org-code class="query-form-el" v-model="dataToQuery.twoLevelOrgCode" />
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="企业名称：" prop="companyId">
                        <company-select v-model="dataToQuery.companyName" style="width:100%" />
                        <!-- <div>
                            <cascader-dom class="query-form-el" ref='queryOrgCascader' @setOrgname='setQueryOrgName' :orgTree="true"
                                          :setCurrentName="{label:dataToQuery.companyName,value:dataToQuery.companyId}"></cascader-dom>
                        </div> -->
                    </FormItem>
                </Col>
                <Col span="8" v-if="!switchFlag">
                    <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                </Col>
                <Col span="8" v-else>
                    <FormItem label='队长：' prop='name'>
                        <Input class='query-form-el' placeholder="请填写队长" type='text' v-model='dataToQuery.name'></Input>
                    </FormItem>
                </Col>
            </Row>
            <Row v-show="switchFlag" class="query-form">

                <Col span="8" offset="16">
                    <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                </Col>
            </Row>
            <Row class="query-form">
                <Col span="24">
                    <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
                    <!-- <Button type="primary" class="ivu-btn-add" icon="md-cloud-download" @click="exportList">导出</Button> -->
                    <download-button :api="exportUrl" :queryForm="dataToQuery" />
                </Col>
            </Row>
        </Form>
        <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!" @on-selection-change='getSelectRows'
          @on-sort-change="sortChange" :loading='pageStatus.loading' @on-expand="onExpand"
               border :columns="columns1" :data="dataTable">
        </Table>
        <!--分页-->
        <Row style="margin-right:10px;">
            <Col span="24">
                <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
                      @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
                      show-total show-sizer show-elevator/>
                <!-- <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange1" @on-page-size-change="pageSizeChange1" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator /> -->
            </Col>
        </Row>
        <!--新增、修改、详情-->
        <Modal :title="mode == 'view' ?'防汛抢险队人员名单详情':'防汛抢险队人员名单'" :transfer=false :mask-closable="false"
               v-model="dialogShow" v-if="dataToView && dialogShow" :width=850 class-name='limit-height-dialog'>
            <Row>
                <Col span="24">
                    <Form ref="dialogForm" :class="mode === 'view'?'modal-view-detail':'modal-form'"
                          :show-message="false" :model="dataToView" :rules="mode === 'view'?{} :ruleCustom"
                          :label-position="mode === 'view'?'right':'top'" :label-width="mode === 'view'?140:null">
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='企业名称：' prop='companyId'>
                                    <div v-if="mode === 'view'">{{dataToView.companyName}}</div>
                                    <cascader-dom v-else ref='orgCascader' @setOrgInfo='setCompanyId' @setOrgname="setCompanyName" :orgTree="true" :currentOrgId="dataToView.companyId"
                                                  :setCurrentName="{label:dataToView.companyName,value:dataToView.companyId}"></cascader-dom>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='队长：' prop='name'>
                                    <div v-if="mode === 'view'">{{ dataToView.name }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写队长" type='text' show-word-limit maxlength="10" v-model='dataToView.name'></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='性别：' prop='sex'>
                                    <div v-if="mode === 'view'">{{ dataToView.sex }}</div>
                                    <Select v-else v-model='dataToView.sex' class='query-form-el'>
                                        <Option value="男" lable="男">男</Option>
                                        <Option value="女" lable="女">女</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='职务：' prop='duties'>
                                    <div v-if="mode === 'view'">{{ dataToView.duties }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写职务" type='text' show-word-limit maxlength="50" v-model='dataToView.duties'></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='任职部门：' prop='department'>
                                    <div v-if="mode === 'view'">{{ dataToView.department }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写任职部门" type='text' show-word-limit maxlength="100" v-model='dataToView.department'></Input>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='联系电话：' prop='telphone'>
                                    <div v-if="mode === 'view'">{{ dataToView.telphone }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写联系电话" type='text' v-model='dataToView.telphone'></Input>
                                </FormItem>
                            </Col>
                        </Row>

                        <Row>
                            <Col v-if="mode !== 'view'" span="23" class="query-form" style="margin-left: 15px">
                                <Button v-if="mode !== 'view'" class="ivu-btn-add" icon="md-add"
                                        @click="itemModel=true,itemAdd=true;detailItem={age:0}">新增队员</Button>
                                <Button icon="md-cloud-upload" class="ivu-btn-add" @click="openUpload">导入队员</Button>
                                <Button icon="md-download" class="ivu-btn-add" @click="downloadModel">下载模板</Button>
                            </Col>
                            <Col span="23" class="query-form" style="margin-left: 15px">

                                <Table highlight-row stripe border style="margin-top:10px;margin-bottom: 10px" :max-height="350" :columns="itemColumn"
                                       :data="dataToView.items">
                                </Table>
                            </Col>
                        </Row>

                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='填报人：' prop='createUserName'>
                                    <div v-if="mode === 'view'">{{ dataToView.createUserName }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写填报人" type='text' readonly
                                           v-model='dataToView.createUserName'></Input>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='填报时间：' prop='createDate'>
                                    <div v-if="mode === 'view'">{{ renderViewDate(dataToView.createDate) }}</div>
                                    <DatePicker v-else class="query-form-el" placeholder="请选择填报时间" readonly
                                                v-model='dataToView.createDate'></DatePicker>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='填报人手机号：' prop='registrantPhone'>
                                    <div v-if="mode === 'view'">{{ dataToView.registrantPhone }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写手机号" type='text' v-model='dataToView.registrantPhone'></Input>
                                </FormItem>
                            </Col>
                            <Col span="11"></Col>
                        </Row>
                    </Form>
                </Col>
            </Row>
            <div slot="footer">
                <Button v-if="mode != 'view'" type="primary" class='ivu-btn-save' @click="submit('dialogForm')">确定</Button>
                <Button v-if="mode != 'view'" type="primary" class='ivu-btn-cancel' @click="handleCancel">取消</Button>
                <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
            </div>
        </Modal>

        <Modal :mask-closable="false" :transfer=false v-model="itemModel" :width=700 title="队员"
               @on-cancel="itemModel=false,detailItem={}">
            <Row>
                <Col span="24">
                    <Form ref="itemForm" :class="'modal-form'" :show-message="false" :model="detailItem" :rules="itemRuleCustom" label-position="top" >
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='姓名：' prop='name'>
                                    <div v-if="mode === 'view'">{{ detailItem.name }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写姓名" type='text' show-word-limit maxlength="10" v-model='detailItem.name'></Input>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='性别：' prop='sex'>
                                    <div v-if="mode === 'view'">{{ detailItem.sex }}</div>
                                    <Select v-else v-model='detailItem.sex' class='query-form-el'>
                                        <Option value="男" lable="男">男</Option>
                                        <Option value="女" lable="女">女</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='职务：' prop='duties'>
                                    <div v-if="mode === 'view'">{{ detailItem.duties }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写职务" type='text' maxlength="50"  show-word-limit v-model='detailItem.duties'></Input>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='任职部门：' prop='department'>
                                    <div v-if="mode === 'view'">{{ detailItem.department }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写任职部门" type='text' maxlength="100"  show-word-limit v-model='detailItem.department'></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='联系电话：' prop='telphone'>
                                    <div v-if="mode === 'view'">{{ detailItem.telphone }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写联系电话" type='text' v-model='detailItem.telphone'></Input>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='年龄：' prop='age'>
                                    <div v-if="mode === 'view'">{{ detailItem.age }}</div>
                                    <InputNumber v-else class='query-form-el' placeholder="请填写年龄" :min="0" type='text' v-model='detailItem.age'></InputNumber>
                                </FormItem>
                            </Col>
                        </Row>


                    </Form>
                </Col>
            </Row>
            <div slot="footer">
                <Button type="primary" class='ivu-btn-save' @click="itemSubmit('itemForm')">确定</Button>
                <Button type="primary" class='ivu-btn-cancel' @click="itemModel=false,detailItem={}">取消</Button>
            </div>
        </Modal>

        <Modal :transfer=false title="批量导入" v-model="modal9" width="800">
            <Form ref="uploadItemData">
                <Row>
                    <i-col span="24">
                        <Upload
                                name="file"
                                type="drag"
                                :format="['xlsx', 'xls']"
                                accept=".xlsx, .xls"
                                :before-upload="handleUpload "
                                action="//jsonplaceholder.typicode.com/posts/">
                            <div style="padding: 20px 0">
                                <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                                <p>请上传xls、xlsx格式的文件</p>
                            </div>
                        </Upload>
                    </i-col>
                </Row>
                <div v-if="fileTrue">
                    <a>{{ uploadMap.file.name }}</a>
                    <Button type="text" icon="md-trash" @click="uploadMap.file = {},fileTrue = false" style="margin-left: 5px;margin-bottom: 3px"/>
                </div>
            </Form>
            <div slot="footer">
                <Button class='ivu-btn-save' :loading="buttonLoading" @click="submitFile()">上传</Button>
                <Button @click="modal9 = false" class="ivu-btn-cancel" >取消</Button>
            </div>
        </Modal>
        <Modal :transfer=false title="异常数据，请检查模板" v-model="modal10" width="800">
            <div :style="{height: divHeight, overflowY: 'auto', overflowX: 'hidden'}">
                <Table ref='table3' :loading="loading3" border :columns="errorColumns" style="margin-top: 0px"
                       :data="errorInfos" width="100%" :height="500" highlight-row stripe size="small"></Table>
            </div>
            <div slot="footer">
                <Button class='ivu-btn-cancel' @click="modal10=false;errorInfos=[]">取消</Button>
            </div>
        </Modal>
    </Layout>
</template>

<script>
    import {Api} from '@/api/index.js'
    import {sessionStorage} from '@/common/cacheUtils.js';
    import {formatDate} from '@/tools/index'
    var cascaderDom = () => import('@/components/cascader-dom.vue');
    import pageCommonFunction from '@/components/pageCommonFunction.js'

    export default {
        components: {cascaderDom},
        data() {
            return {
                ...this.createCommonDataField(),
                columns1: [
                    {type:'expand', width:30,
                        fixed: 'left',
                        _disableExpand:true,
                        render:(h,params)=>{
                            return h('Table',{
                                props: {
                                    columns: [
                                        { key:'name',title: '姓名',  align: 'center', minWidth: 120,  },
                                        { key:'sex',title: '性别',  align: 'center', minWidth: 120,  },
                                        { key:'duties',title: '职务',  align: 'center', minWidth: 120,  },
                                        { key:'department',title: '任职部门',  align: 'center', minWidth: 120,  },
                                        { key:'telphone',title: '联系电话',  align: 'center', minWidth: 120,  },
                                        { key:'age',title: '年龄',  align: 'center', minWidth: 120,  },
                                    ],//表头
                                    data: params.row.items,//内部表格展示的数据
                                },
                            })//我这里使用的是表格，大家也可以根据自己的实际情况更换别的组件
                        }
                    },
                    {title: '序号', width: 80, fixed: 'left', align: 'center', render: this.indexColumnsRender},
                    { key:'companyName',title: '单位名称',  align: 'center', minWidth: 150, },
                    { key:'name',title: '队长',  align: 'center', minWidth: 120,  },
                    { key:'sex',title: '性别',  align: 'center', minWidth: 120,  },
                    { key:'duties',title: '职务',  align: 'center', minWidth: 120,  },
                    { key:'department',title: '任职部门',  align: 'center', minWidth: 120,  },
                    { key:'telphone',title: '联系电话',  align: 'center', minWidth: 120,  },
                    { key:'belongOrgName',title: '所属二级集团',  align: 'center', minWidth: 150, },
                    {key: 'createDate', title: '填报时间', sortable: "custom", align: 'center', minWidth: 120,
                        render: (h,params)=>{return h('span',this.renderViewDate(params.row.createDate))}},
                    {key: 'registrantPhone', title: '填报人手机号', align: 'center', minWidth: 120,},
                    this.getActionColumns()
                ],
                ruleCustom: {
                    name: [ { required: true, message: '请填写队长', trigger: 'change',}],
                    sex: [ { required: true, message: '请填写性别', trigger: 'change',}],
                    duties: [ { required: true, message: '请填写职务', trigger: 'change',}],
                    department: [ { required: true, message: '请填写任职部门', trigger: 'change',}],
                    telphone: [ {
                        validator: (rule, value, callback) => {
                            if (!(/^1[3456789]\d{9}$/.test(this.dataToView.telphone))) {
                                callback(' ');
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'blur'
                    }],
                    registrantPhone: [{
                        validator: (rule, value, callback) => {
                            if (!(/^1[3456789]\d{9}$/.test(this.dataToView.registrantPhone))) {
                                callback(' ');
                                // this.$Message.error("请填写有效的的手机号")
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'blur'
                    }],
                },
                tableHeight: 10,
                dictMap:{},
                detailItem:{},
                itemModel:false,
                itemAdd:false,
                columns2: [
                    {title: '序号', width: 70, align: 'center', render: this.indexColumnsRender},
                    { key:'name',title: '姓名',  align: 'center', minWidth: 120,  },
                    { key:'sex',title: '性别',  align: 'center', minWidth: 120,  },
                    { key:'duties',title: '职务',  align: 'center', minWidth: 120,  },
                    { key:'department',title: '任职部门',  align: 'center', minWidth: 120,  },
                    { key:'telphone',title: '联系电话',  align: 'center', minWidth: 120,  },
                    { key:'age',title: '年龄',  align: 'center', minWidth: 120,  },
                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        width: 110,
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {fontSize: '13px',},
                                    on: {
                                        click: () => {
                                            this.detailItem = {...params.row}
                                            this.itemModel = true
                                            this.itemAdd = false
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {props: {type: 'vertical'}}, ''),
                                h('A', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {fontSize: '13px',color: 'red'},
                                    on: {
                                        click: () => {
                                            this.dataToView.items.splice(params.index,1)
                                        }
                                    }
                                }, '删除'),
                            ])
                        }
                    }
                ],
                itemRuleCustom: {
                    name: [ { required: true, message: '请填写姓名', trigger: 'change',}],
                    sex: [ { required: true, message: '请填写性别', trigger: 'change',}],
                    duties: [ { required: true, message: '请填写职务', trigger: 'change',}],
                    department: [ { required: true, message: '请填写任职部门', trigger: 'change',}],
                    telphone: [ {
                        validator: (rule, value, callback) => {
                            if (!(/^1[3456789]\d{9}$/.test(this.detailItem.telphone))) {
                                callback(' ');
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'blur'
                    }],
                    age: [ { required: true, message: '请填写年龄', trigger: 'change',type:'number'}],
                },
                // api
                queryUrl: Api.queryFloodPrevention.replace('{{table}}', 'RescuePersonnel'),
                exportUrl: Api.exportFloodPrevention.replace('{{table}}', 'RescuePersonnel'),
                deleteUrl: Api.deleteFloodPrevention.replace('{{table}}', 'RescuePersonnel'),
                getUrl: Api.getFloodPrevention.replace('{{table}}', 'RescuePersonnel'),
                updateUrl: Api.updateFloodPrevention.replace('{{table}}', 'RescuePersonnel'),
                saveUrl: Api.saveFloodPrevention.replace('{{table}}', 'RescuePersonnel'),
                buttonLoading: false,

                uploadMap:{},
                modal9: false,
                modal10: false,
                fileTrue: false,
                errorInfos: [],
                errorColumns: [
                    { key:'num',title: '序号', width: 70, align: 'center'},
                    { key:'name',title: '姓名',  align: 'center', minWidth: 120,  },
                    { key:'sex',title: '性别',  align: 'center', minWidth: 120,  },
                    { key:'duties',title: '职务',  align: 'center', minWidth: 120,  },
                    { key:'department',title: '任职部门',  align: 'center', minWidth: 120,  },
                    { key:'telphone',title: '联系电话',  align: 'center', minWidth: 120,  },
                    { key:'age',title: '年龄',  align: 'center', minWidth: 120,  },
                ],
            }
        },
        computed: {
            itemColumn() {
                const columns = [...this.columns2];
                const columns1 = []
                columns.forEach(item => {
                    if (this.mode !== 'view') {
                        columns1.push(item)
                    } else {
                        if (item.key !== 'action') {
                            columns1.push(item)
                        }
                    }
                })
                return columns1
            },
        },
        async mounted() {
            this.setTableHeight();
            this.query();
        },
        methods: {
            ...pageCommonFunction,
            openUpload(){
                this.modal9 = true;
                this.fileTrue = false
                this.uploadMap = {}
            },
            handleUpload (file) {
                this.uploadMap.file = file;
                this.fileTrue = true;
                return false;
            },
            submitFile(){
                let formData = new FormData();
                formData.append("file", this.uploadMap.file);
                this.$http.post(this.queryUrl + '/upload', formData).then((res) => {
                    if(res.data.status == 201){
                        this.$Message.error(res.data.msg);
                        this.modal10 = true;
                        let title = ['name','sex','duties','department','telphone','age']
                        res.data.data.map((i=>{
                            let cellClassName = {}
                            for (let k in title) {
                                if (i[title[k]] == null){
                                    cellClassName[title[k]] = "table-info-cell-red";
                                }
                            }
                            i.cellClassName = cellClassName;
                        }));
                        this.errorInfos = res.data.data;
                    }else if(res.data.status == 200){
                        this.$Message.success("批量导入成功");
                        let dataItems = res.data.data
                        dataItems.forEach(item =>{
                            this.dataToView.items.push(item);
                        })
                        this.modal9 = false;
                        this.fileTrue = false
                    }
                }).catch(e => {
                    console.log(e)
                    this.$Message.error("导入失败！请检查导入文档的格式是否正确");
                })
            },
            downloadModel(){
                this.$http.get(this.queryUrl + '/upload/model',{
                    params: {
                        type: this.$route.query.noticeCategory
                    },
                    responseType: 'arraybuffer'
                }).then((res) => {
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: "application/vnd.ms-excel"
                    })
                    aLink.href = URL.createObjectURL(blob);
                    aLink.download = "队员导入模板.xlsx" //标题
                    aLink.click();
                    document.body.appendChild(aLink);
                })
            },

            itemSubmit(name){
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.$Modal.confirm({
                            title: '提示',
                            content: '<p>是否要提交？</p>',
                            onOk: () => {
                                let _this = this
                                _this.dataToView.items.splice()
                                if (_this.itemAdd) {
                                    _this.dataToView.items.push(_this.detailItem)
                                } else {
                                    _this.dataToView.items[_this.detailItem._index]= _this.detailItem
                                }
                                _this.itemModel = false
                            },
                            onCancel: () => {}
                        })
                    }else {
                        this.$Message.error('请填报完整!');
                    }
                })
            },

            deleteData(params) {
                this.deleteDateAjax(params);
            },

            query() {

                this.queryAjax();
            },
            submit(name) {
                if (this.dataToView.items.length < 1) {
                    this.$Message.warning('队员至少填报一条');
                } else {
                    this.submitAjax(name);
                }
            },
            createEmptyDataToAdd() {
                return {
                    areas: 0,
                    id: this.get_uuid(),
                    idFiles: [],
                    items: [],
                    age: 1
                }
            },
            async afterDataToViewInit() {
                // await this.getFiles1('id', 'examSelect');
            },

        }
    }
</script>

<style lang='css' scoped>
    @import '../../../index.css';
</style>
